<!-- 设备管理 -->
<template>
  <div class="jq-table h-full flex-col">
    <div class="packageCardcontainer">
      <template
        v-for="boxContent in contentList"
        :key="boxContent?.title"
      >
        <PackageCard
          class="card"
          :boxContent="boxContent"
        />
      </template>
    </div>
    <SearchForm
      @handle-reset-form-datas="handleResetFormDatas"
      :searchForm="searchForm"
      @handle-search="handleSearch"
      @chanFormValue="chanFormValue"
    />
    <div
      class="page-card h-full"
      v-loading="loading"
    >
      <JqTable
        :tableColumn="tableColumn"
        :tableButtons="tableButtons"
        :itemsButtons="itemsButtons"
        :data="tableData"
        :page="page"

        :loading="loading"
        @handle-size-change="handleSizeChange"
        @handle-current-change="handleCurrentChange"
      >
      <template #statusText>
          <el-table-column
            show-overflow-tooltip
            :min-width="100"
            prop="statusText"
            label="状态"
            fit="true"
            show-header="true"
            align="left"
          >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span :class="scope.row.status ===  1 ? `point1` : scope.row.status ===  2 ? `point2`: 'point3'"></span>
                <span>{{ scope.row['statusText'] }}</span>
              </div>
            </template>
          </el-table-column>
      </template>
      </JqTable>
      <!--  :isSelect="true" -->
      <!-- <AddOrUpdate
        ref="addOrUpdateRef"
        @clear-form-datas="clearFormDatas"
        @handle-form-value="handleFormValue"
        @on-cancel="onCancel"
        @on-confirm="onConfirm"
      /> -->
      <AddOrUpdate v-if="showDialog" v-model:dialogVisible="showDialog" ref="addOrUpdateRef" :dialogDatas="dialogDatas"
        @update-list="updateList" />
      <Password ref="passwordRef" />
      <BatchModify
        ref="batchModifyRef"
        @on-confirm="onConfirmBatchModify"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'CheckPointEquipment' }); //设备管理
interface Row {
  id: number;
  status: number;
}
import { reactive, ref, onBeforeMount, computed, watch,nextTick } from 'vue';
import { useTable } from '@/hooks/useTable';
import {
  getDeviceList,
  getStatistics,
  enableOrDisablRequest,
  addDeviceRequest,
  getDeviceByIdRequest,
  exportRequest,
  editDeviceRequest
} from '@/api/checkPointEquipment';
import { orgOptionsRequest, getEnumListRequest, getCheckPointsOptionsRequest } from '@/api/common';

import { JqTable } from '@/components/Table/index';
// import { AddOrUpdate } from '@/components/Add-or-update/index';

import { Password, BatchModify,AddOrUpdate } from './components';
import { PackageCard } from '@/components/PackageCard/index';
import type { FormInstance } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useRouteStore } from '@/store';
const showDialog = ref(false)
const routeStore = useRouteStore();

const addOrUpdateRef = ref();

const passwordRef = ref();
const batchModifyRef = ref();

let orgIdDatas = reactive([]); //归属组织下拉数据
let dialogDatas = reactive({});

let enumListDatas = reactive({}); //设备状态下拉数据
let enumListTypeDatas = reactive({}); //设备类型下拉数据
let checkPointsOptionsDatas = reactive({}); //归属检测点下拉数据
let checkPointsOptionsDatasForForm = reactive({}); //归属检测点下拉数据(数据筛选)
let showDatasForDialog = ref({}); //编辑按钮回显数据

/* 多选选中的数据 */
let multipleSelection = reactive([]);

let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '设备ID',
    required: true,
    placeholder:'请输入设备ID',
    eName: 'deviceId'
  },
  {
    type: 'select',
    value: '',
    label: '归属组织',
    required: true,
    placeholder: '全部',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'select',
    value: '',
    label: '设备状态',
    required: true,
    options: () => {
      return enumListDatas;
    },
    eName: 'status'
  },
  {
    type: 'selectson',
    value: '',
    label: '归属检测点',
    required: true,
    options: () => {
      return checkPointsOptionsDatasForForm;
    },
    eName: 'checkPointsId'
  },
  {
    type: 'select',
    value: '',
    label: '设备类型',
    required: true,
    options: () => {
      return enumListTypeDatas;
    },
    eName: 'deviceType'
  },
  {
    type: 'date',
    value: '',
    label: '创建时间',
    eName: 'createTimeStart'
  }
]);
let dialogForConfigDatas = reactive([
  {
    type: 'input1',
    value: null,
    label: '设备ID',
    required: true,
    placeholder:'请输入设备ID',
    eName: 'deviceId',
  },
  {
    type: 'select',
    value: '',
    label: '归属组织机构',
    required: true,
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },

  {
    type: 'selectson',
    value: '',
    label: '归属检测点',
    required: true,
    options: () => {
        return checkPointsOptionsDatas;
    },
    eName: 'checkPointsId'
  },
  {
    type: 'select',
    value: '',
    label: '设备类型',
    required: true,
    options: () => {
      return enumListTypeDatas;
    },
    eName: 'deviceType'
  },
  {
    type: 'select',
    value: '',
    label: '启用状态',
    required: true,
    options: () => {
      return enumListDatas;
    },
    eName: 'status'
  }
]);

const batchModifyDatas = reactive({
  title: '批量修改归属',
  type: 'select',
  value: '',
  name: 'orgId',
  placeholder: '全部',
  options: () => {

    return orgIdDatas;
  },
  eName: 'orgId',
  multipleSelection: []
});
let searchFormParams = reactive({}); //查询参数

let passwordDialogDatas = reactive({
  // 设备ID: '',
  // 健康顾问手机号: '',
  // 该设备登录密码为: ''
});
const tableColumn = reactive([
  //内置
  { label: '设备ID', prop: 'deviceId',minWidth: '80' }, //接口缺少字段，待更新？
  { label: '归属组织机构', prop: 'orgName',minWidth: '120'  },
  { label: '归属检测点', prop: 'pointName',minWidth: '120'  },
  { label: '设备类型', prop: 'deviceTypeText',minWidth: '80' },
  { label: '创建时间', prop: 'createTime',minWidth: '170' },
  { label: '最后一次检测时间', prop: 'lastCheckTime',minWidth: '170' },
  { label: '状态', prop: 'statusText',minWidth: '80',slot: true },
  { label: '已检测次数', prop: 'detectedCount',minWidth: '110' }
]);
let tableButtonsOld = reactive([
  //来源于数据

  {
    id: 20,
    type: 'primary',
    label: '添加',
    perms: 'device:btn:create',
    onClick:async () => {
      showDialog.value = true
      dialogDatas = {
        title: '新增',
        type: 'add',
        datas: dialogForConfigDatas
      };
    }
  },
  {
    id: 28,
    type: '',
    label: '导出',
    perms: 'device:btn:export',
    onClick: async (row: {}) => {
      const params = Object.assign({}, searchFormParams, {
        pageNum: page.page,
        pageSize: page.pageSize
      });
      const data: any = await exportRequest(params);
      if (data.code === 2000) {
        ElMessage.success('导出成功');
      }
      window.open(data.data);
    }
  },

]);
let itemsButtonsOld = reactive([
  //来源于数据

  {
    id: 22,
    type: 'success',
    label: '查看',
    perms: 'device:btn:view',
    onClick: (row: Row) => {
      // router.push('/myTest');
      showDialog.value = true
      dialogDatas = {
        title: '查看',
        type: 'check',
        datas: row
      };
    }
  },
  {
    id: 21,
    type: 'primary',
    eName: 'edit',
    label: '编辑',
    perms: 'device:btn:edit',
    onClick: (row:[]) => {
      showDialog.value = true
      dialogDatas = {
        title: '编辑',
        type: 'edit',
        datas: row
      };
      console.log(row,"rowrowrowrow")
    }
  },
  {
    id: 25,
    type: 'success',
    label: '查看密码',
    perms: 'device:btn:passwd',
    onClick: (row: []) => {
      dialogDatas = {
        title: '查看密码',
        type: '',
        row: row,
        datas: passwordDialogDatas
      };
      onPassword(dialogDatas);
    }
  },
  {
    id: 24,
    eName: 'pause',
    perms: 'device:btn:status',
    statusConfig:{
        1:'启用',
        2:'停用',
        // 3:'待激活'
      },
    onClick: async (row: any) => {
      getEnableOrDisablDatas({ id: row.id, status: row.status === 1 ? 2 : 1 }).then(res=> {
        getList();
        ElMessage.success('修改成功')
      })
    }
  },
  // {
  //   eName: 'stop',
  //   id: 24,
  //   type: 'warning',
  //   label: '停用',
  //   onClick: async (row: Row) => {
  //     await getEnableOrDisablDatas({ id: row.id, status: row.status === 1 ? 2 : 1 });
  //     getList();
  //   }
  // }
]);
const contentList = reactive([
  {
    title: '本月新增设备',
    number: '',
    bgUrl: 'Bg.png',
    iconUrl: 'Icon.png'
  },
  {
    title: '设备总数',
    number: '',
    bgUrl: 'Bg2.png',
    iconUrl: 'Icon2.png'
  },
  {
    title: '使用中的设备',
    number: '',
    bgUrl: 'Bg3.png',
    iconUrl: 'Icon3.png'
  },
  {
    title: '停用的设备',
    number: '',
    bgUrl: 'Bg4.png',
    iconUrl: 'Icon4.png'
  }
]);
watch(searchForm[1], async (newVal, oldVal) => {
  //数据筛选
  /* 获取归属检测点数据 */
  
  if (newVal.value) {
    const data: any = await getCheckPointsOptionsRequest({ orgId: newVal.value });
    checkPointsOptionsDatasForForm = data.data;
  }
});
watch(dialogForConfigDatas[1], async (newVal, oldVal) => {
  /* 获取归属检测点数据 */
  // dialogForConfigDatas[2].value=''
  if (newVal.value) {
    const data: any = await getCheckPointsOptionsRequest({ orgId: newVal.value });
    checkPointsOptionsDatas = data.data;
    console.log(dialogForConfigDatas,"dialogForConfigDatas")
    dialogForConfigDatas.forEach(async (d) => {
    if(d.eName=='checkPointsId'){
      d.value=''
    }
  });
  }
});
const updateList = () => {
  getList();
  getStatisticsDatas()
  showDialog.value = false
}

/* 获取当前菜单数据 */
const currentMenudatas = computed(() => routeStore.currentMenudatas);

const onPassword = (data?: Recordable) => {
  passwordRef.value.init(data);
};
/* 表单查询 */
const handleSearch = async (searchFormParamsDatats: {}) => {
  searchFormParamsDatats.deviceId=Number(searchFormParamsDatats.deviceId);
  if (searchFormParamsDatats.checkPointsId instanceof Array) {
    searchFormParamsDatats.checkPointsId = '';
  }
  Object.assign(searchFormParams, searchFormParamsDatats);
  await getList();
  // handleResetFormDatas();
};
const { tableData, page, loading, getList, resetParams, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: getDeviceList,
    params: () => searchFormParams
  });
const chanFormValue = (formParamsDatats: {}) => {
  searchFormParams = formParamsDatats;
};

const handleResetFormDatas = () => {
  searchFormParams = {};
  searchForm = searchForm.map((item) => {
    if (item.value) {
      item.value = '';
    }
    return item;
  });
  getList();
};

const getStatisticsDatas = async () => {
  const data: any = await getStatistics({});
  const statisticsDatas = data.data;
  contentList[0].number = statisticsDatas.newDeviceThisMonth;
  contentList[1].number = statisticsDatas.totalDevice;
  contentList[2].number = statisticsDatas.usingDevice;
  contentList[3].number = statisticsDatas.stopDevice;
};
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas = data.data;
};
const onConfirmBatchModify = () => {
  getList();
};

/* 获取设备状态数据 */
const getEnumListDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'DeviceStatusEnum' });
  enumListDatas = data.data;
};

/* 获取设备类型 */
const getEnumListTypeDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'DeviceTypeEnum' });
  enumListTypeDatas = data.data;
};


/* 更新停用/启用 */
const getEnableOrDisablDatas = async (param: object) => {
  const data: any = await enableOrDisablRequest(param);
};

const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
const tableButtons = ref([] as any[])
const itemsButtons = ref([] as any[])
onBeforeMount(() => {
  getStatisticsDatas();
  getOrgOptionsDatas();
  getEnumListDatas();
  getEnumListTypeDatas();
    tableButtons.value = tableButtonsPermission(tableButtonsOld, currentMenudatas.value?.tableButtons || []); //tableButtons根据数据返回按钮信息控制权限
    itemsButtons.value = tableButtonsPermission(itemsButtonsOld, currentMenudatas.value?.itemsButtons || []); //itemButtons根据数据返回按钮信息控制权限
});
</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  > .card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    margin-bottom: 10px;
    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
